package com.bxd.baodan.imger;

/**
 * Created by Administrator on 2017/4/1.
 */

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

import com.bxd.baodan.app.Constant;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class AsyncTaskImageLoad extends AsyncTask<String, Integer, Bitmap> {
    private String path = Constant.IMAGE_AD;
    private String fileName;

    public AsyncTaskImageLoad(String fileName) {
        this.fileName = fileName;
    }

    //运行在子线程中
    protected Bitmap doInBackground(String... params) {
        try {
            URL url = new URL(params[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            if (conn.getResponseCode() == 200) {
                InputStream input = conn.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(input);
                return bitmap;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute(Bitmap result) {
        if (fileName != null && result != null) {
            try {
                saveFile(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        super.onPostExecute(result);
    }


    /**
     * 保存文件
     *
     * @param bm
     * @throws IOException
     */
    public void saveFile(Bitmap bm)  {
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File myCaptureFile = new File(path + fileName);
        if (!myCaptureFile.exists()) {
            try {

                BufferedOutputStream bos = null;
                bos = new BufferedOutputStream(
                        new FileOutputStream(myCaptureFile));
                bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);

                   bos.flush();
                    bos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

       }
    }
}
